<template>
  <div>
    <div
      style="
        width: 100%;
        height: 4vh;
        background-color: #191e37;
        line-height: 4vh;
        color: white;
        border-radius: 8px;
      "
    >
      <span>收益指标</span>
    </div>

    <!-- Tab 切换按钮 -->
    <div class="tabs">
      <div
        v-for="(tab, index) in tabs"
        :key="index"
        class="tab"
        :class="{ active: activeTab === index }"
        @click="switchTab(index)"
      >
        {{ tab }}
      </div>
    </div>

    <div class="tab-content">
      <div v-if="activeTab === 0">
        <div
          ref="chartContainer"
          style="width: 100%; height: 40vh; background-color: #191e37"
        ></div>
      </div>
      <div v-if="activeTab === 1">
        <div style="width: 100%; height: 40vh; background-color: #191e37">
          222
        </div>
      </div>
      <div v-if="activeTab === 2">
        <div style="width: 100%; height: 40vh; background-color: #191e37">
          333
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  data() {
    return {
      tabs: ["近七日", "当月", "当年"],
      activeTab: 0,
      chartInstance: null,
    };
  },
  watch: {
    activeTab(newIndex, oldIndex) {
      if (newIndex === 0 && oldIndex !== 0) {
        this.initChart();
      } else if (oldIndex === 0) {
        this.destroyChart();
      }
    },
  },
  methods: {
    switchTab(index) {
      this.activeTab = index;
    },
    initChart() {
      this.$nextTick(() => {
        if (this.chartInstance) {
          this.chartInstance.dispose();
        }
        const chartContainer = this.$refs.chartContainer;
        this.chartInstance = echarts.init(chartContainer);

        const option = {
          xAxis: {
            type: "category",
            data: ["A", "B", "C"],
          },
          yAxis: {
            type: "value",
          },
          series: [
            {
              data: [120, 200, 200],
              type: "line",
            },
          ],
        };

        this.chartInstance.setOption(option);
      });
    },
    destroyChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
      }
    },
  },
  mounted() {
    this.initChart();
  },
};
</script>

<style scoped>
.tabs {
  display: flex;
  justify-content: space-around;
  background-color: #191e37;
  width: 100%;
  border-radius: 8px;
}

.tab {
  padding: 10px 20px;
  cursor: pointer;
  transition: color 0.3s;
}

.tab.active {
  color: #3578f2;
}

.tab:not(.active):hover {
  text-decoration: underline;
}

.tab-content {
  font-size: 16px;
}
</style>
